package com.sdy.mvc.service.impl;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.sdy.common.constant.Constants;
import com.sdy.common.model.FileObj;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.service.FileService;
import com.sdy.common.utils.OsPathUtil;
import com.sdy.common.utils.RandomUtil;
import com.sdy.mvc.distributed.NacosCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Created by zzq on 2017-08-23.
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired(required = false)
    private NacosCommonService nacosCommonService;
    private static String REMOTE_FS_UPLOAD_PATH = "/file/upload";
    @Value(("${fs.domain:}"))
    private String fsDomain;

    @Override
    public FileObj saveFile(MultipartFile file, String typeStr) throws Exception {
        if (StringUtil.isBlank(typeStr)) {
            typeStr = "common";
        }
        String originFileName = file.getOriginalFilename();
        String path = OsPathUtil.convertWithOs(Constants.UPLOAD_FILE_PATH + "/" + typeStr);
        String fileName = System.currentTimeMillis() + "_" + RandomUtil.produceNumber(5) + originFileName.substring(originFileName.lastIndexOf('.'));
        File f = new File(path, fileName);
        File p = new File(path);
        if (!p.exists()) {
            p.mkdirs();
        }
        file.transferTo(f);
        return new FileObj().setFileSize((int) file.getSize()).setFileName(originFileName).setPath(Constants.UPLOAD_FILE_PATH + "/" + typeStr + "/" + fileName);
    }

    @Override
    public String getFsUploadAddr() {
        if (StringUtil.isBlank(fsDomain)) {
            if (nacosCommonService != null) {
                List<Instance> fsInstanceList = nacosCommonService.listInstance("sdy-fs");
                if (!fsInstanceList.isEmpty()) {
                    Instance fsInstance = fsInstanceList.get(0);
                    return "http://" + fsInstance.getIp() + ":" + fsInstance.getPort() + REMOTE_FS_UPLOAD_PATH;
                }
                return null;
            } else {
                return REMOTE_FS_UPLOAD_PATH;
            }
        }
        return fsDomain + REMOTE_FS_UPLOAD_PATH;
    }
}
